#裁剪原始图像
import os
import cv2
from tqdm import tqdm
# 输入文件夹路径和输出文件夹路径
input_folder = r'E:\satLocate\fusai\basemap\raster'
output_folder = r'E:\satLocate\fusai\basemap\crop'

# 确保输出文件夹存在
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 定义裁剪参数
# image_size = 5000  # 原始影像尺寸
crop_size = 600  # 子影像尺寸
overlap = int(crop_size * 0.4)  # 重叠部分尺寸
# 生成子影像坐标
# y_coords = range(0, image_size, crop_size - overlap)
# x_coords = range(0, image_size, crop_size - overlap)
image_files = tqdm([file for file in os.listdir(input_folder) if file.endswith(".jpg")])
# 遍历输入文件夹中的所有.TIF文件
for file_name in image_files:
        image_files.set_description("Image Crop %s" % file_name) # 设置描述
        # 读取图像文件
        image_path = os.path.join(input_folder, file_name)
        img = cv2.imread(image_path)
        h,w,_ = img.shape
        y_coords = range(0, h, crop_size - overlap)
        x_coords = range(0, w, crop_size - overlap)
        #生成子影像
        for y in y_coords:
            for x in x_coords:
                # 确定子影像的结束位置
                x_end = x + crop_size
                y_end = y + crop_size
                # 裁剪子影像
                if(x + crop_size > w):
                    x = w - crop_size
                    x_end = w
                if(y + crop_size > h):
                    y = h - crop_size
                    y_end = h
                cropped_img = img[y:y_end, x:x_end]

                # 保存子影像到输出文件夹
                output_path = os.path.join(output_folder, f"{file_name[:-4]}_{x}_{y}_{x_end-1}_{y_end-1}.jpg")
                cv2.imwrite(output_path, cropped_img)

print("所有影像裁剪完成")